package com.ijianji.module_play_video.model

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.fenghuajueli.lib_data.database.DaoManager
import com.fenghuajueli.lib_data.database.DaoUtils
import com.fenghuajueli.lib_data.entity.db.VideoInfoEntity
import com.fenghuajueli.lib_data.entity.VideoResponseListEntity
import com.fenghuajueli.lib_data.entity.db.VideoInfoEntityDao
import com.fenghuajueli.libbasecoreui.listener.BaseCallBackListener
import com.fenghuajueli.libbasecoreui.videoapi.VideoPlayList
import com.fenghuajueli.libbasecoreui.viewmodel.BaseViewModel
import com.ijianji.module_play_video.utils.RandomUtils
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext

class PlayVideoModel : BaseViewModel(), CoroutineScope by CoroutineScope(SupervisorJob() + Dispatchers.IO) {


    /**
     * 视频列表数据观察者
     */
    val videoListData = MutableLiveData<MutableList<VideoInfoEntity>>()

    /**
     * 推荐视频列表数据观察者
     */
    val recommendVideoListData = MutableLiveData<MutableList<VideoInfoEntity>>()

    /**
     * 视频url的观察者
     */
    val videoUrlData = MutableLiveData<String>()


    /**
     * 收藏状态更新的观察者
     */
    val collectionStatusData = MutableLiveData<Boolean>()

    /**
     * 检测是否收藏的状态 这个不弹toast提示
     */
    val collectionCheckStatusData = MutableLiveData<Boolean>()


    /**
     * 收藏列表
     */
    val collectionVideoListData = MutableLiveData<MutableList<VideoInfoEntity>>()

    /**
     * 播放记录列表
     */
    val playHistoryVideoListData = MutableLiveData<MutableList<VideoInfoEntity>>()

    /**
     * 获取视频播单列表
     */
    /**
     * @param owner
     * @param pid
     * @param tag 区分属于那一次请求的
     */
    fun loadVideoList(owner: LifecycleOwner, pid: String, pageSize: Int) {
        VideoPlayList.getVideoList(owner, pid, pageSize, object : BaseCallBackListener<VideoResponseListEntity> {
            override fun onSuccess(data: VideoResponseListEntity?) {
                hideLoading()
                data?.search_lists?.let {
                    RandomUtils.createRandom(it)
                    videoListData.postValue(it)
                }
            }

            override fun onFailed(error: String?) {
                showToast(error)
                hideLoading()
            }

            override fun onHandlerStart() {
                showLoading("视频获取中...")
            }
        })
    }


    /**
     * 获取视频推荐播单列表
     */
    /**
     * @param owner
     * @param pid
     * @param tag 区分属于那一次请求的
     */
    fun loadRecommendVideoList(owner: LifecycleOwner, pid: String, pageSize: Int) {
        VideoPlayList.getVideoList(owner, pid, pageSize, object : BaseCallBackListener<VideoResponseListEntity> {
            override fun onSuccess(data: VideoResponseListEntity?) {
                hideLoading()
                data?.search_lists?.let {
                    RandomUtils.createRandom(it)
                    recommendVideoListData.postValue(it)
                }
            }

            override fun onFailed(error: String?) {
                showToast(error)
                hideLoading()
            }

            override fun onHandlerStart() {
                showLoading("视频获取中...")
            }
        })
    }


    fun getVideoRealUrl(owner: LifecycleOwner, vid: String) {
        VideoPlayList.getRealVideoPath(owner, vid, object : BaseCallBackListener<String> {
            override fun onSuccess(data: String?) {
                hideLoading()
                data?.let {
                    videoUrlData.postValue(it)
                }
            }

            override fun onFailed(error: String?) {
                hideLoading()
                showToast(error)
                finishActivity()
            }

            override fun onHandlerStart() {
                showLoading()
            }
        })
    }


    /**
     * 收藏视频
     */
    fun collectionVideo(videoInfoEntity: VideoInfoEntity) {
        launch(coroutineContext) {
            videoInfoEntity.isCollection = true
            if (!videoInfoEntity.isPlay) {
                //如果当前实体是没有播放过 则需要查询是否有播放记录
                val list = DaoUtils.getVideoCollectionManager().query(VideoInfoEntity::class.java,
                        VideoInfoEntityDao.Properties.Vid.eq(videoInfoEntity.vid), VideoInfoEntityDao.Properties.IsPlay.eq(1))
                if (list.size > 0) {
                    videoInfoEntity.isPlay = true
                }
            }
            val success = DaoUtils.getVideoCollectionManager().insertData(videoInfoEntity)
            if (success) {
                collectionStatusData.postValue(true)
            }
        }
    }


    /**
     * 取消收藏视频
     */
    fun cancelCollectionVideo(videoInfoEntity: VideoInfoEntity) {
        launch(coroutineContext) {
            videoInfoEntity.isCollection = false
            if (!videoInfoEntity.isPlay) {
                //如果当前实体是没有播放过 则需要查询是否有播放记录
                val list = DaoUtils.getVideoCollectionManager().query(VideoInfoEntity::class.java,
                        VideoInfoEntityDao.Properties.Vid.eq(videoInfoEntity.vid), VideoInfoEntityDao.Properties.IsPlay.eq(1))
                if (list.size > 0) {
                    videoInfoEntity.isPlay = true
                }
            }
            val success = DaoUtils.getVideoCollectionManager().updateData(videoInfoEntity)
            if (success) {
                collectionStatusData.postValue(false)
            }
        }
    }

    fun checkVideoIsCollection(videoInfoEntity: VideoInfoEntity) {
        launch(coroutineContext) {
            val data = DaoUtils.getVideoCollectionManager().query(VideoInfoEntity::class.java,
                    VideoInfoEntityDao.Properties.Vid.eq(videoInfoEntity.vid), VideoInfoEntityDao.Properties.IsCollection.eq(1))
            LogUtils.d("检查是否存在收藏：${(data != null && data.size > 0)}")
            collectionCheckStatusData.postValue((data != null && data.size > 0))
        }
    }


    /**
     * 加载收藏列表
     */
    fun loadCollectionList() {
        showLoading()
        launch(coroutineContext) {
            val list = DaoUtils.getVideoCollectionManager().query(VideoInfoEntity::class.java,
                    VideoInfoEntityDao.Properties.IsCollection.eq(1))
            if (list != null) {
                collectionVideoListData.postValue(list)
            }
            hideLoading()
        }
    }

    /**
     * 加载播放记录列表
     */
    fun loadPlayHistoryList() {
        showLoading()
        launch(coroutineContext) {
            val list = DaoUtils.getVideoCollectionManager().query(VideoInfoEntity::class.java,
                    VideoInfoEntityDao.Properties.IsPlay.eq(1))
            if (list != null) {
                playHistoryVideoListData.postValue(list)
            }
            hideLoading()
        }
    }


    /**
     * 添加播放记录
     */
    fun addPlayHistory(videoInfoEntity: VideoInfoEntity) {
        launch(coroutineContext) {
            videoInfoEntity.isPlay = true
            if (!videoInfoEntity.isCollection) {
                //如果当前实体是没有收藏过的，则要先查询是否已经收藏了 防止被修改属性
                val list = DaoUtils.getVideoCollectionManager().query(VideoInfoEntity::class.java,
                        VideoInfoEntityDao.Properties.Vid.eq(videoInfoEntity.vid), VideoInfoEntityDao.Properties.IsCollection.eq(1))
                if (list.size > 0) {
                    videoInfoEntity.isCollection = true
                }
            }
            DaoUtils.getVideoCollectionManager().insertData(videoInfoEntity)
        }
    }
}